"""
难度：中等
给你一个链表的头节点 head ，旋转链表，将链表每个节点向右移动 k 个位置。
示例 1：
输入：head = [1,2,3,4,5], k = 2
输出：[4,5,1,2,3]
示例 2：
输入：head = [0,1,2], k = 4
输出：[2,0,1]
"""

# Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
class Solution:
    def rotateRight(self, head: ListNode, k: int) -> ListNode:
        if k == 0 or not head or not head.next:
            return head
        
        n = 1
        cur = head
        while cur.next:
            cur = cur.next
            n += 1
        
        # if (add := n - k % n) == n:
            # return head
        
        cur.next = head
        while add:
            cur = cur.next
            add -= 1
        
        ret = cur.next
        cur.next = None
        return ret

    def rotateRight(self, head: ListNode, k: int) -> ListNode:
        if not head:
            return None
        length = 0
        temp = head
        while temp.next:
            length += 1
            temp = temp.next
        
        temp.next = head
        k = k % (length + 1)
        temp =head
        for i in range(length-k):
            temp = temp.next
        head = temp.next
        temp.next = None
        return head
        

    
